﻿using HIWSystem.Common;
using HIWSystem.UserControls;
using HIWSystem.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using GalaSoft.MvvmLight.Messaging;

namespace HIWSystem.Views
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        DataTable dt = new DataTable();
        Dictionary<string, MenuItem> dicMenuItemInfos = new Dictionary<string, MenuItem>();
        public MainWindow()
        {
            InitializeComponent();
            ViewManager.Register("Login", typeof(LogIn), null);
            Messenger.Default.Register<string>(this, "ShowTabItem", ShowTabByExternalModule);
        }
 
        List<TabItem> lstTabItem = new List<TabItem>();
        private void AddData_Click(object sender, RoutedEventArgs e)
        {
            //string stateCode = string.Empty;
            //string stateMsg = string.Empty;

            //WebReference.FTPWebService FtpWebService = new WebReference.FTPWebService();
            //Console.WriteLine(FtpWebService.HelloWorld());
            //WebReference.FTPConnectionInfo FtpConnInfo = new WebReference.FTPConnectionInfo();
            //FtpConnInfo.IP = "192.168.135.32";
            //FtpConnInfo.Port = "21";
            //FtpConnInfo.User = "administrator";
            //FtpConnInfo.Password = "Dell123";
            //FtpConnInfo.RootPath = "Test";
            //string fileName = AppDomain.CurrentDomain.BaseDirectory + "UploadData.dll";
            //bool uploadResult = false;//上传结果
            //string msg = string.Empty;
            //uploadResult = FtpWebService.Upload(FtpConnInfo, fileName, out msg);
            //if (uploadResult)
            //{
            //    System.Windows.Forms.MessageBox.Show("上传成功!");
            //}
            //else
            //{
            //    System.Windows.Forms.MessageBox.Show(msg);
            //}

            ////RecordModel rm = new RecordModel();
            ////rm.ChipID = "";
            ////rm.QR = "908PA221600125";
            ////rm.Result = "Pass";
            ////rm.Error = "-1";
            ////rm.Current = "56.3";
            ////rm.MTF_LU = "56.75";
            ////rm.MTF_RU = "56.67";
            ////rm.MTF_Center = "67.37";
            ////rm.MTF_LD = "58.18";
            ////rm.MTF_RD = "57.47";
            ////rm.YShading_TL = "55.5";
            ////rm.YShading_TR = "55.5";
            ////rm.YShading_BL = "55.5";
            ////rm.BlemishNum = "0";
            ////rm.BlemishMaxArea = "0";
            ////rm.OpticalCenterOffsetX = "-3";
            ////rm.OpticalCenterOffsetY = "9";
            ////rm.Noise = "32.97";
            ////InsertData.InsertRecord(rm, out stateCode, out stateMsg);

            ////if (stateCode=="OK")
            ////{
            ////   MessageBox.Show(stateMsg);
            ////}
            ////if (stateCode=="NO")
            ////{
            ////   MessageBox.Show(stateMsg);
            ////}
        }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            RemoveTabItem();
        }

        private void Exit_Click(object sender, RoutedEventArgs e)
        {
            Environment.Exit(0);
        }

        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {

        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            UserControlManage.Register("添加机种", new AddPartNumber());
            UserControlManage.Register("添加站位", new AddStation());
            UserControlManage.Register("添加流程", new AddRouting());
            UserControlManage.Register("工单开立", new ReleaseWO());
            UserControlManage.Register("添加员工", new AddEmployee());
            UserControlManage.Register("标签打印", new LabelPrint());
            UserControlManage.Register("菜单管理", new MenuManage());
            UserControlManage.Register("员工菜单管理", new EmployeeMenuManage());
            UserControlManage.Register("入库", new END());
            UserControlManage.Register("包装", new PackingPrint());
            UserControlManage.Register("互调录入", new IMDInfoEntry());
            UserControlManage.Register("质量录入", new QCInfoEntry());
            UserControlManage.Register("调试录入", new TUNNINGInfoEntry());
            UserControlManage.Register("工单查询", new WOQuery());
            UserControlManage.Register("调试查询", new TUNNINGInfoQuery());
            UserControlManage.Register("组装录入", new AssemblyInfoEntry());
            UserControlManage.Register("产量统计", new StatisticsStationOutput());
            UserControlManage.Register("机种查询", new PartNumberQuery());
            UserControlManage.Register("出货", new Ship());
            UserControlManage.Register("计划产量", new PlanOutputInfoEntry());
            UserControlManage.Register("查询产量", new PlanOutputInfoQuery());
            UserControlManage.Register("出货报告", new ShipReport());
            UserControlManage.Register("互调良率", new IMDYieldQuery());
            UserControlManage.Register("互调报告", new IMDReportGenerate());
            UserControlManage.Register("绑定站位", new AddBindStation());
            UserControlManage.Register("ATE汇总", new ATEReportSummary());
            UserControlManage.Register("测试软件管理", new TestSoftwareManage());
            UserControlManage.Register("标签配置", new LabelConfig());
            UserControlManage.Register("测试记录作废", new TestTrackingObsolete());
            this.LogInStateInfo.Text = LogInInfo.User + "_登录成功!";
            //this.Width = SystemParameters.WorkArea.Size.Width;
            //this.Height = SystemParameters.WorkArea.Size.Height;
            //this.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            BindMenuItem();
        }
        //绑定菜单
        void BindMenuItem()
        {
            dt = BusinessProcess.GetMenuItems();
            var menuItemConfig = dt.AsEnumerable();
            try
            {
                var maxMenuItemLevel = menuItemConfig.Max(x => Convert.ToInt32(x["MenuItemLevel"].ToString()));
                //添加一级菜单
                var topMenu = menuItemConfig.Where(x => Convert.ToInt32(x["MenuItemLevel"].ToString()) == 1);
                foreach (var top in topMenu)
                {
                    MenuItem tmpTopMenuItem = new MenuItem();
                    tmpTopMenuItem.Header = top["MenuCn"].ToString();
                    this.MenuControl.Items.Add(tmpTopMenuItem);
                    //添加二级菜单
                    var secondMenu = menuItemConfig.Where(x => Convert.ToInt32(x["MenuItemLevel"].ToString()) == 2 && x["ParentHeader"].ToString() == top["Header"].ToString());
                    foreach (var second in secondMenu)
                    {
                        MenuItem tmpSecondMenuItem = new MenuItem();
                        tmpSecondMenuItem.Header = second["MenuCn"].ToString();
                        tmpSecondMenuItem.Click += MenuItemClickHandler;
                        tmpTopMenuItem.Items.Add(tmpSecondMenuItem);
                        //可以添加三级菜单
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        /// <summary>
        /// 通过外部模块显示选项卡
        /// </summary>
        /// <param name="tabHeader">选项卡头名称</param>
        private void ShowTabByExternalModule(string tabHeader)
        {
            TabItem tabItem = new TabItem();
            tabItem.Header = tabHeader;
            tabItem.Content = UserControlManage.Fetch(tabItem.Header.ToString());
            AddTabItem(tabItem);
        }
        void MenuItemClickHandler(object sender, RoutedEventArgs e)
        {
            MenuItem cMenuItem = (MenuItem)sender;
            if (cMenuItem.Header.ToString() == "退出")
            {
                Environment.Exit(0);
            }
            //重新登录时弹出登录框
            if (cMenuItem.Header.ToString()=="重新登录")
            {
                this.Hide();
                ViewManager.Show("Login");
            }
            TabItem tabItem = new TabItem();
            tabItem.Header = cMenuItem.Header;
            tabItem.Content = UserControlManage.Fetch(tabItem.Header.ToString());
            AddTabItem(tabItem);
        }

        private void AddTabItem(TabItem tab)
        {
            var result = lstTabItem.Count(x => x.Header == tab.Header);
            if (result == 0)
            {

                lstTabItem.Add(tab);
                TabControl.Items.Add(tab);
                TabControl.SelectedIndex = lstTabItem.Count - 1;
            }
            else
            {
                for (int i = 0; i < lstTabItem.Count; i++)
                {
                    if (lstTabItem[i].Header == tab.Header)
                    {
                        TabControl.SelectedIndex = i;
                    }
                }
            }

        }
        private void RemoveTabItem()
        {
            //存储角标因为TabControl_SelectionChanged事件发生后角标会变化(目前这个Bug还没有解决)
            int selectedIndex = TabControl.SelectedIndex;
            TabControl.Items.RemoveAt(selectedIndex);
            if (TabControl.SelectedIndex == -1)
            {
                lstTabItem.RemoveAt(0);
            }
            else
            {
                lstTabItem.RemoveAt(selectedIndex);
            }

        }

        void pMenuItem_Click(object sender, RoutedEventArgs e)
        {
            throw new NotImplementedException();
        }

        void childMenuItem_Click(object sender, RoutedEventArgs e)
        {
            MenuItem cMenuItem = (MenuItem)sender;
            TabItem tabItem = new TabItem();
            tabItem.Header = cMenuItem.Header;
            AddTabItem(tabItem);
        }

        void childMenuItem_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            MenuItem cMenuItem = (MenuItem)sender;
            TabItem tabItem = new TabItem();
            tabItem.Header = cMenuItem.Header;
            AddTabItem(tabItem);
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            Environment.Exit(0);
        }

        private void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.Source.GetType() != typeof(TabControl))
            {
                e.Handled = true;
            }
        }
    }
}